from flask import Blueprint,jsonify,request
import pdfplumber
import re,os
from datetime import datetime


alipay_info_bp = Blueprint('alipayInfo', __name__)
from Test import db
from config.config import Config





class AlipayInfo(db.Model):
    __tablename__ = 'alipay_info'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    type = db.Column(db.String(255), comment='收/支')
    trade = db.Column(db.String(255), comment='交易对方')
    description = db.Column(db.String(255), comment='商品说明')
    payWay = db.Column(db.String(255), comment='收/付款方式')
    price = db.Column(db.String(255), comment='金额')
    transactionNum = db.Column(db.String(255), comment='交易订单号')
    saleOrderNum = db.Column(db.String(255), comment='商家订单号')
    tradeTime = db.Column(db.String(255), comment='交易时间')
    number = db.Column(db.String(255), comment='编号')
    name = db.Column(db.String(255), comment='姓名')
    identificationNumber = db.Column(db.String(255), comment='证件号码')
    alipayAccount = db.Column(db.String(255), comment='支付宝账号信息')
    etl_dt = db.Column(db.DateTime, default=datetime.utcnow)  # 导入时间


    def __str__(self):
        return (f"交易类型: {self.type}\n"
                f"交易对方: {self.trade}\n"
                f"商品说明: {self.description}\n"
                f"付款方式: {self.payWay}\n"
                f"金额: {self.price}\n"
                f"交易订单号: {self.transactionNum}\n"
                f"商家订单号: {self.saleOrderNum}\n"
                f"交易时间: {self.tradeTime}\n"
                f"编号: {self.number}\n"
                f"姓名: {self.name}\n"
                f"证件号码: {self.identificationNumber}\n"
                f"支付宝账号信息: {self.alipayAccount}\n")


@alipay_info_bp.route('/add-formfile', methods=['POST'])
def add_formfile():
    # 设置上传文件的目录（临时目录）
    UPLOAD_FOLDER = Config.UPLOAD_FOLDER
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    # 检查请求中是否有文件
    if 'file' not in request.files:
        return jsonify({'data': '', 'msg': '没有文件上传', 'status': 400})

    file = request.files['file']

    # 检查文件是否有效
    if file.filename == '':
        return jsonify({'data': '', 'msg': '没有选择文件', 'status': 400})

    if file and allowed_file(file.filename):  # 确保有一个 allowed_file 函数

    # pdf_file = '/Users/wubing/Desktop/pdfData/支付宝副本.pdf'
        try:
            # 保存上传的文件
            pdf_file_path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(pdf_file_path)
            data_list = getDataFromAliPdf(pdf_file_path)
            for data in data_list:
                db.session.add(data)
                db.session.commit()
            return jsonify({
                'data': '',
                'message': '成功导入' + len(data_list).__str__() + '条数据',
                'status': 200
            })
        except Exception as e:
            print(str(e))
            return jsonify({'data': '', 'msg': '导入数据失败，失败原因为:'+str(e),'status':500 })



def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def getDataFromAliPdf(pdf_file: str) -> list[AlipayInfo]:
    # pdf_file = '/Users/wubing/Desktop/pdfData/支付宝副本.pdf'
    ##使用正则提取文本中的用户信息
    all_pages_content = ""
    with pdfplumber.open(pdf_file) as pdf:
        for page in pdf.pages:
            all_pages_content += page.extract_text()
    # 使用正则表达式匹配编号
    ##编号
    number = ''
    ##姓名
    name = ''
    ##证件号码
    identificationNumber = ''
    ##支付宝账号信息
    alipayAccount = ''

    pattern = r'编号: (\d+)'
    match = re.search(pattern, all_pages_content)
    if match:
        number = match.group(1)

    pattern = r'兹证明:([\u4e00-\u9fa5]+)\('
    match = re.search(pattern, all_pages_content)
    if match:
        name = match.group(1)

    pattern = r'证件号码:(\d{6}\d{4}\d{2}\d{2}\d{3}\d{1})'
    match = re.search(pattern, all_pages_content)
    if match:
        identificationNumber = match.group(1)

    pattern = r'支付宝账号(\d+)'
    match = re.search(pattern, all_pages_content)
    if match:
        alipayAccount = match.group(1)

    with pdfplumber.open(pdf_file) as pdf:
        tables = []
        # 遍历所有的页面
        for page in pdf.pages:
            tables.extend(page.extract_tables())

    result_list = []


    # 遍历并打印每个表格
    table_data = tables[0]
    for index, table in enumerate(table_data):
        if index > 2:
            type = table[0].replace('\n', '')
            trade = table[1].replace('\n', '')
            description = table[2].replace('\n', '')
            payWay = table[3].replace('\n', '')
            price = table[4].replace('\n', '')
            transactionNum = table[5].replace('\n', '')
            saleOrderNum = table[6].replace('\n', '')
            tradeTime = table[7].replace('\n', ' ')

            object = AlipayInfo()
            object.type = type
            object.trade = trade
            object.description = description
            object.payWay = payWay
            object.price = price
            object.transactionNum = transactionNum
            object.saleOrderNum = saleOrderNum
            object.tradeTime = tradeTime
            object.number = number
            object.name = name
            object.identificationNumber = identificationNumber
            object.alipayAccount = alipayAccount

            result_list.append(object)
    return result_list